package com.youdianstar.app.ui

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.safframework.eventbus.EventBus

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityOrderListBinding
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.network.BaseApiPagingObserver
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.widget.adapter.FooterAdapter
import com.youdianstar.app.adapter.OrderPagingAdapter
import com.youdianstar.app.adapter.OrderOPAdapter
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.entity.NewOrderInfo

import kotlinx.coroutines.flow.collectLatest
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: OrderListActivity
 * Author: 82149 Create: 2021/11/11 16:33
 * Changes (from 2021/11/11)
 * --------------------------------------------------
 * description: 网点列表
 * ---------------------------------------------------
 *
 */
class OrderListActivity :BaseActivity<ActivityOrderListBinding, OrderViewModel>(){

    override fun layoutId(): Int = R.layout.activity_order_list

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): OrderViewModel{
        val model: OrderViewModel by viewModel()
        return model
    }

    private var mOrderPagingAdapter = OrderPagingAdapter()
    private var mNewOrderAdapter: OrderOPAdapter? = null

    override fun initViewLayout() {
        super.initViewLayout()
        
        // 初始化HeadBar，使用和订单详情页面一致的方式
        mBinding.headBar.initTitle(this, getString(R.string.order_list_title))
        
        mBinding.run {
            // 初始化时设置LayoutManager
            rcOrders.layoutManager = LinearLayoutManager(this@OrderListActivity)
            
            // 刷新监听
            swOrderList.setOnRefreshListener {
                loadListData()
            }

            loadListData()
        }

        EventBus.post(BusEntity(DataCode.CLOSE_DRAWER))//关闭侧边栏
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        
        // 使用新的订单列表API
        mViewModel.newOrderListLiveData.observe(this, object : BaseApiResultObserver<List<Any>>(false) {
            override fun onDataResult(data: List<Any>?) {
                super.onDataResult(data)
                // 隐藏loading对话框和刷新状态
                dismissDialog()
                mBinding.swOrderList.isRefreshing = false
                
                data?.let { orderList ->
                    if (orderList.isEmpty()) {
                        // 显示空状态
                        showEmptyState(getString(R.string.order_empty))
                    } else {
                        // 截取前20个订单
                        val limitedOrderList = orderList.take(20)
                        
                        // 打印订单信息
                        android.util.Log.d("OrderListActivity", "获取到订单数据: ${orderList.size}条，显示前20条")
                        limitedOrderList.forEachIndexed { index, order ->
                            when (order) {
                                is NewOrderInfo -> {
                                    android.util.Log.d("OrderListActivity", "订单${index + 1}: UUID=${order.uuidLastSix}, 状态=${order.usingStatus}, 费用=${order.fee}, 支付=${order.pay}, 地址=${order.box1SiteName}")
                                }
                                else -> {
                                    android.util.Log.d("OrderListActivity", "订单${index + 1}: 未知类型")
                                }
                            }
                        }
                        
                        // 创建新的适配器并设置到RecyclerView
                        mNewOrderAdapter = OrderOPAdapter(this@OrderListActivity, limitedOrderList)
                        mBinding.rcOrders.adapter = mNewOrderAdapter
                        
                        // 显示列表，隐藏空状态和错误状态
                        mBinding.rcOrders.visibility = View.VISIBLE
                        mBinding.llEmpty.visibility = View.GONE
                        mBinding.llError.visibility = View.GONE
                    }
                } ?: run {
                    // 数据为null，显示空状态
                    showEmptyState(getString(R.string.order_empty))
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                android.util.Log.e("OrderListActivity", "获取订单列表失败: code=$code, error=$e")
                
                // 隐藏loading对话框和刷新状态
                dismissDialog()
                mBinding.swOrderList.isRefreshing = false
                
                // 显示错误状态
                val errorMessage = e ?: "网络错误，请检查网络连接"
                showErrorState(errorMessage)
            }

            override fun onDataEmpty() {
                super.onDataEmpty()
                android.util.Log.d("OrderListActivity", "订单列表为空")
                
                // 隐藏loading对话框和刷新状态
                dismissDialog()
                mBinding.swOrderList.isRefreshing = false
                
                // 显示空状态
                showEmptyState(getString(R.string.order_empty))
            }
        })
    }

    override fun initClickEvent() {
        // 重试按钮
        mBinding.btnRetry.setOnClickListener {
            loadListData()
        }
    }
    
    override fun onResume() {
        super.onResume()
        
        // 每次进入页面时刷新订单列表
        loadListData()
    }

    private fun loadListData() {
        // 显示loading对话框
        showLoadingDialog("")
        
        // 隐藏所有状态视图
        mBinding.run {
            rcOrders.visibility = View.GONE
            llEmpty.visibility = View.GONE
            llError.visibility = View.GONE
        }
        
        // 使用新的订单列表API
        mViewModel.getNewOrderList()
    }

    /**
     * 显示空状态
     */
    private fun showEmptyState(message: String) {
        mBinding.run {
            rcOrders.visibility = View.GONE
            llEmpty.visibility = View.VISIBLE
            llError.visibility = View.GONE
            tvEmptyMessage.text = message
        }
    }

    /**
     * 显示错误状态
     */
    private fun showErrorState(message: String) {
        mBinding.run {
            rcOrders.visibility = View.GONE
            llEmpty.visibility = View.GONE
            llError.visibility = View.VISIBLE
            tvErrorMessage.text = message
        }
    }

}